package com.ikas.ai.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

/**
 * 日期时间处理公共类.
 *
 * @author 黄旭辉
 */
@SuppressWarnings("all")
public class DateTimeUtil {

    private static Logger logger = LoggerFactory.getLogger(DateTimeUtil.class);
    public static final String MONTHFORMATTPL = "yyyyMM";
    public static final String DATEFORMATTPL = "yyyy-MM-dd";
    public static final String DATETIMEFORMATTPL = "yyyy-MM-dd HH:mm:ss";

    public static final String DATETIMEFMINORMATTPL = "yyyy-MM-dd HH:mm";
    public static final String DATETIMEUTCFORMATTPL = "yyyy-MM-dd'T'HH:mm:ss";
    public static final String DATETIMEMSFORMATTPL = "yyyy-MM-dd HH:mm:ss.SSS";
    public static final String SIMPLEDATEFORMATTPL = "yyyyMMdd";
    public static final String SIMPLEDATETIMEFORMATTPL = "yyyyMMddHHmmss";
    public static final String SIMPLEDATETIMEMINUTEFORMATTPL = "yyyyMMddHHmm";
    public static final String TIMESIMPLEFORMATTPL = "HH:mm";
    public static final String TIMEFORMATTPL = "HH:mm:ss";
    public static final String DDFORMATTPL = "dd";
    private static ResourceBundle resource = null;

    private DateTimeUtil() {

    }

    /**
     * 日期格式。
     *
     * @return 日期格式
     */
    public static String getDatePattern() {
        return DATEFORMATTPL;
    }

    /**
     * 时间格式。
     *
     * @return 时间格式
     */
    public static String getTimePattern() {
        return TIMEFORMATTPL;
    }

    /**
     * 简单时间格式。
     *
     * @return 简单时间格式
     */
    public static String getSimpleTimePattern() {
        return TIMESIMPLEFORMATTPL;
    }

    /**
     * 日期时间格式。
     *
     * @return 时间日期格式
     */
    public static String getDateTimePattern() {
        return DATETIMEFORMATTPL;
    }

    /**
     * 获取当前时间字符串
     *
     * @return
     */
    public static String getDateTimeString() {
        return getDateTimeString(false);
    }

    /**
     * 获取当前日期字符串
     *
     * @return
     */
    public static String getSimpleDateString() {
        SimpleDateFormat sdf = new SimpleDateFormat(SIMPLEDATEFORMATTPL);
        return sdf.format(new Date());
    }

    /**
     * 获取当前日期字符串
     *
     * @return
     */
    public static String getSimpleDateString(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(SIMPLEDATEFORMATTPL);
        return sdf.format(date);
    }

    public static String plusEndTime(String time, Integer second) {
        DateTime dateTime = DateUtil.parse(time, DateTimeUtil.DATETIMEFORMATTPL, Locale.CHINA);
        dateTime.offset(DateField.SECOND, second);
        return DateUtil.format(dateTime, DateTimeUtil.DATETIMEFORMATTPL);
    }

    /**
     * 获取当前日期字符串
     *
     * @return
     */
    public static String getDateString() {
        return getDateString(new Date());
    }

    /**
     * 获取当前日期字符串
     *
     * @param date
     * @return
     */
    public static String getDateString(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMATTPL);
        return sdf.format(date);
    }

    /**
     * 获取当天dd
     *
     * @param date
     * @return
     */
    public static String getDDString(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(DDFORMATTPL);
        return sdf.format(date);
    }

    /**
     * 获取当前时间字符串
     *
     * @return
     */
    public static String getTimeString() {
        return getTimeString(new Date());
    }

    /**
     * 获取当前时间字符串
     *
     * @param date
     * @return
     */
    public static String getTimeString(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(TIMEFORMATTPL);
        return sdf.format(date);
    }

    /**
     * 获取当前时间字符串
     *
     * @return
     */
    public static String getSimpleTimeString() {
        return getSimpleTimeString(new Date());
    }

    /**
     * 获取当前时间字符串
     *
     * @param date
     * @return
     */
    public static String getSimpleTimeString(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(TIMESIMPLEFORMATTPL);
        return sdf.format(date);
    }

    /**
     * 获取当前时间字符串
     *
     * @param date
     * @return
     */
    public static String getSimpleTimeString(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat(DATETIMEFORMATTPL);
        return sdf.format(timestamp);
    }

    /**
     * 获取当前时间字符串hh:mm
     *
     * @param date
     * @return
     */
    public static String getSimpleMinTimeString(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat(DATETIMEFMINORMATTPL);
        return sdf.format(timestamp);
    }

    /**
     * 获取当前时间字符串
     *
     * @param date
     * @return
     */
    public static String getMillTimeString(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat(DATETIMEMSFORMATTPL);
        return sdf.format(timestamp);
    }

    /**
     * 格式化时间
     *
     * @param ms
     * @return
     */
    public static String formatTime(Long ms) {
        Integer ss = 1000;
        Integer mi = ss * 60;
        Integer hh = mi * 60;
        Integer dd = hh * 24;

        Long day = ms / dd;
        Long hour = (ms - day * dd) / hh;
        Long minute = (ms - day * dd - hour * hh) / mi;
        Long second = (ms - day * dd - hour * hh - minute * mi) / ss;
        Long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;

        StringBuffer sb = new StringBuffer();
        if (day > 0) {
            sb.append(day + "天");
        }
        if (hour > 0) {
            sb.append(hour + "小时");
        }
        if (minute > 0) {
            sb.append(minute + "分");
        }
        if (second > 0) {
            sb.append(second + "秒");
        }
        if (milliSecond > 0) {
            sb.append(milliSecond + "毫秒");
        }
        return sb.toString();
    }

    /**
     * 格式化时间时/分
     *
     * @param ms
     * @return
     */
    public static String formatTimeStr(Long ms) {
        Integer ss = 1000;
        Integer mi = ss * 60;
        Integer hh = mi * 60;
        Integer dd = hh * 24;

        Long day = ms / dd;
        Long hour = (ms - day * dd) / hh;
        Long minute = (ms - day * dd - hour * hh) / mi;

        StringBuffer sb = new StringBuffer();
        if (day > 0) {
            sb.append(day + "天");
        }
        if (hour > 0) {
            sb.append(hour + "小时");
        }
        if (minute > 0) {
            sb.append(minute + "分");
        }
        return sb.toString();
    }


    /**
     * 获取当前时间字符串
     *
     * @param withMillisecond
     * @return
     */
    public static String getDateTimeString(boolean withMillisecond) {
        return getDateTimeString(new Date(), withMillisecond);
    }

    /**
     * 获取当前时间字符串
     *
     * @param date
     * @return
     */
    public static String getDateTimeString(Date date) {
        return getDateTimeString(date, false);
    }

    /**
     * 获取当前时间字符串
     *
     * @param date
     * @param withMillisecond
     * @return
     */
    public static String getDateTimeString(Date date, boolean withMillisecond) {
        SimpleDateFormat sdf = null;
        if (withMillisecond) {
            sdf = new SimpleDateFormat(DATETIMEMSFORMATTPL);
        } else {
            sdf = new SimpleDateFormat(DATETIMEFORMATTPL);
        }
        return sdf.format(date);
    }

    /**
     * 获取当前日期字符串
     *
     * @return
     */
    public static String getSimpleDateTimeString() {
        SimpleDateFormat sdf = new SimpleDateFormat(SIMPLEDATETIMEFORMATTPL);
        return sdf.format(new Date());
    }

    /**
     * 获取当前日期字符串
     *
     * @return
     */
    public static String getSimpleDateTimeString(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(SIMPLEDATETIMEFORMATTPL);
        return sdf.format(date);
    }

    /**
     * 日期转为字符串.
     *
     * @param date 要格式化的日期
     * @return 日期字符串
     */
    public static String format(Date date) {
        if (date == null) {
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(getDateTimePattern());
        return sdf.format(date);
    }

    /**
     * 字符串转换为日期时间.
     *
     * @param source 日期字符串
     * @return 日期
     */
    public static Date parse(String source) {
        Date rtn = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(getDateTimePattern());
            rtn = sdf.parse(source);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return rtn;
    }

    /**
     * 获得WEB服务器UTC时间。
     *
     * @return 返回WEB服务器UTC时间
     */
    public static Date getWebServerUTCDate() {
        Calendar calendar = new GregorianCalendar();
        TimeZone zone = calendar.getTimeZone();
        return getUTCDate(calendar.getTime(), zone);
    }

    /**
     * 获得UTC时间.
     *
     * @param date 本地时间
     * @param zone 本地所在时区
     * @return UTC时间
     */
    public static Date getUTCDate(Date date, TimeZone zone) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.setTimeZone(zone);
        calendar.add(Calendar.MILLISECOND, -zone.getRawOffset());
        return calendar.getTime();
    }

    /**
     * 获得本地时间.
     *
     * @param date UTC时间
     * @param zone 本地所在时区
     * @return 本地时间
     */
    public static Date getLocalDate(Date date, TimeZone zone) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.setTimeZone(zone);
        calendar.add(Calendar.MILLISECOND, zone.getRawOffset());
        return calendar.getTime();
    }

    /**
     * 字符串转换为时间
     *
     * @param source
     * @return
     */
    public static Date getDate(String source) {
        return getDateTimeS(source, false);
    }

    /**
     * 获得当前时间的日期
     *
     * @return Date 不包括time，只有日期
     */
    public static Date getCurDate() {
        String curDateStr = getDateString();
        return parse(curDateStr + " 00:00:00");
    }

    /**
     * 获取昨天日期字符串
     *
     * @return
     */
    public static String getYesterdayDateStr() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1); //得到前一天
        Date date = calendar.getTime();
        return getDateString(date);
    }

    /**
     * 获取指定日期的字符串,例如获取明天 ，后天，昨天，前天，上前天....
     *
     * @param 当天 i=0
     * @return
     */
    public static String getDefineDateStr(int i) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, i);
        Date date = calendar.getTime();
        return getDateString(date);
    }

    /**
     * 获取指定日期时间的字符串,例如获取明天 ，后天，昨天，前天，上前天....
     *
     * @param 当天 i=0
     * @return
     */
    public static String getDefineDateTimeStr(int i) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, i);
        Date date = calendar.getTime();
        return getDateTimeString(date);
    }

    /**
     * 获取指定日期时间的long毫秒数,例如获取明天 ，后天，昨天，前天，上前天....
     *
     * @param 当天 i=0
     * @return
     */
    public static long getDefineDateTimeLong(int i) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, i);
        Date date = calendar.getTime();
        return date.getTime();
    }

    /**
     * 获取昨天的日期
     *
     * @return
     */
    public static Date getYesterdayDate() {
        String datestring = getYesterdayDateStr();
        return parse(datestring + " 00:00:00");
    }

    /**
     * 获取昨天的日期
     *
     * @return
     */
    public static Date getYesterdayDateEnd() {
        String datestring = getYesterdayDateStr();
        return parse(datestring + " 23:59:59");
    }

    /**
     * 字符串转换为时间
     *
     * @param source
     * @param withMillisecond
     * @return
     */
    public static Timestamp getDateTimeS(String datestr, boolean withMillisecond) {
        try {
            SimpleDateFormat sdf = null;
            if (withMillisecond) {
                sdf = new SimpleDateFormat(DATETIMEMSFORMATTPL);
            } else {
                sdf = new SimpleDateFormat(DATETIMEFORMATTPL);
            }
            return new Timestamp(sdf.parse(datestr).getTime());
        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 字符串转换为时间
     *
     * @param source
     * @return
     */
    public static Date getDate(String source, String pattern) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            return sdf.parse(source);
        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }


    /**
     * 字符串转换为时间
     *
     * @param source
     * @return
     */
    public static Date getDateCore(String source, String pattern) {
        try {
            return DateUtil.parse(source, pattern).toJdkDate();
        } catch (Exception ignored) {
            throw new RuntimeException(ignored.getMessage());
        }
    }

    /**
     * 字符串转换为时间
     *
     * @param source
     * @return
     */
    public static Timestamp getTimestamp(String source, String pattern) {
        try {
            return DateUtil.parse(source, pattern).toTimestamp();
        } catch (Exception ignored) {
            throw new RuntimeException(ignored.getMessage());
        }
    }

    /**
     * 年月日时分秒转换为时间
     *
     * @param year
     * @param month
     * @param day
     * @param hour
     * @param minute
     * @param second
     * @return
     */
    public static Date getDate(int year, int month, int day, int hour, int minute, int second) {
        try {
            Calendar c = Calendar.getInstance();
            c.set(year, month - 1, day, hour, minute, second); //月份从0开始

            return c.getTime();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * @param date 要格式话的日期 yyyy-MM-dd HH:mm:ss
     * @return 今天 HH:mm:ss or 昨天 HH:mm:ss or MM-dd HH:mm:ss
     * @throws ParseException
     */
    public static String convertDateFormat(String date) throws ParseException {
        SimpleDateFormat allformat = new SimpleDateFormat(DATETIMEFORMATTPL);
        SimpleDateFormat dateformat = new SimpleDateFormat(DATEFORMATTPL);
        SimpleDateFormat timeformat = new SimpleDateFormat(TIMEFORMATTPL);
        SimpleDateFormat datetimeformat = new SimpleDateFormat("MM-dd HH:mm:ss");

        Date myDate = allformat.parse(date);
        Calendar cal = Calendar.getInstance();
        String dateNow = dateformat.format(cal.getTime());
        cal.add(Calendar.DATE, -1);
        String dateYesterday = dateformat.format(cal.getTime());

        if (dateformat.format(myDate).equals(dateNow)) {
            return resource.getString("today") + " " + timeformat.format(myDate);
        } else if (dateformat.format(myDate).equals(dateYesterday)) {
            return resource.getString("yesterday") + " " + timeformat.format(myDate);
        } else {
            return datetimeformat.format(myDate);
        }
    }

    /**
     * 两个日期相隔的天数
     *
     * @param c1 :起始日期
     * @param c2 :结束日期
     * @return c2-c1相隔的天数
     */
    public static double daysBetween(Calendar c1, Calendar c2) {
        // 将时分秒都置0
        Calendar startTime = Calendar.getInstance();
        startTime.clear();
        startTime.set(c1.get(Calendar.YEAR), c1.get(Calendar.MONTH), c1.get(Calendar.DAY_OF_MONTH),
                c1.get(Calendar.HOUR_OF_DAY), c1.get(Calendar.MINUTE), c1.get(Calendar.SECOND));

        Calendar endTime = Calendar.getInstance();
        endTime.clear();
        endTime.set(c2.get(Calendar.YEAR), c2.get(Calendar.MONTH), c2.get(Calendar.DAY_OF_MONTH),
                c2.get(Calendar.HOUR_OF_DAY), c2.get(Calendar.MINUTE), c2.get(Calendar.SECOND));

        long time1 = startTime.getTimeInMillis();
        long time2 = endTime.getTimeInMillis();
        return (time2 - time1) / (1000 * 3600 * 24 + 0d);
    }

    /**
     * 两个日期相隔的天数
     *
     * @param beginDate :起始日期
     * @param endDate   :结束日期
     * @return beginDate-endDate相隔的天数
     */
    public static int daysBetween(Date beginDate, Date endDate) {
        Calendar startTime = Calendar.getInstance();
        startTime.setTime(clearTime(beginDate));

        Calendar endTime = Calendar.getInstance();
        endTime.setTime(clearTime(endDate));

        long time1 = startTime.getTimeInMillis();
        long time2 = endTime.getTimeInMillis();
        long betweenDays = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(betweenDays));
    }

    /**
     * 清空日期的时分秒
     *
     * @param time
     * @return 返回时间为00:00:00的日期对象
     */
    public static Date clearTime(Date time) {
        Date date = null;
        if (null == time) {
            return date;
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(getDatePattern());
            date = sdf.parse(sdf.format(time));
        } catch (ParseException e) {
            logger.error(e.getMessage(), e);
        }
        return date;
    }

    /**
     * 两个日期相隔的秒数
     *
     * @param c1 起始日期
     * @param c2 结束日期
     * @return c2- c1相隔的秒数
     */
    public static long sencondsBetween(Calendar c1, Calendar c2) {
        Calendar startTime = Calendar.getInstance();
        startTime.clear();
        startTime.set(c1.get(Calendar.YEAR), c1.get(Calendar.MONTH), c1.get(Calendar.DAY_OF_MONTH),
                c1.get(Calendar.HOUR_OF_DAY), c1.get(Calendar.MINUTE), c1.get(Calendar.SECOND));

        Calendar endTime = Calendar.getInstance();
        endTime.clear();
        endTime.set(c2.get(Calendar.YEAR), c2.get(Calendar.MONTH), c2.get(Calendar.DAY_OF_MONTH),
                c2.get(Calendar.HOUR_OF_DAY), c2.get(Calendar.MINUTE), c2.get(Calendar.SECOND));

        long time1 = startTime.getTimeInMillis();
        long time2 = endTime.getTimeInMillis();
        return (time2 - time1) / 1000L;
    }

    /**
     * 复制一个calendar 避免调用add的时候原始对象产生副作用
     *
     * @return
     */
    public static Calendar cloneCalendar(Calendar cal) {
        Calendar c = Calendar.getInstance();
        c.clear();
        c.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH),
                cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND));
        c.set(Calendar.MILLISECOND, cal.get(Calendar.MILLISECOND));
        return c;
    }

    /**
     * 获取当前系统时间，带时分秒
     *
     * @return
     */
    public static Timestamp getCurrentTimestamp() {
        return new Timestamp(System.currentTimeMillis());
    }

    /**
     * 根据日期和时间进行拼接
     *
     * @param date 格式 yyyy-MM-dd
     * @param time 格式 hh:mm
     * @return
     */
    public static Date concatDateTime(Date date, String time) {
        return parse(getDateString(date) + " " + time + ":00");
    }

    /**
     * 获取到月份的时间：yyyyMM
     *
     * @return
     */
    public static String getMonthDateString() {
        SimpleDateFormat sdf = new SimpleDateFormat(MONTHFORMATTPL);
        return sdf.format(new Date());
    }

    /**
     * 获取当前的月份时间
     *
     * @return
     */
    public static Date getCurMonthDate() {
        Date rtn = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(MONTHFORMATTPL);
            String curDate = getMonthDateString();
            rtn = sdf.parse(curDate);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return rtn;
    }

    public static boolean isFirstDayOfMonth() {
        boolean isFirstDay = false;
        Calendar calendar = Calendar.getInstance();
        int today = calendar.get(Calendar.DAY_OF_MONTH);
        if (today == 1) {
            isFirstDay = true;
        }
        return isFirstDay;
    }

    public static String getBeforeMonth() {
        SimpleDateFormat sdf = new SimpleDateFormat(MONTHFORMATTPL);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1);
        Date beforMonthDate = calendar.getTime();
        return sdf.format(beforMonthDate);
    }

    /**
     * 获取一年内时间字符串列表(时间格式：yyyyMM)
     *
     * @return
     */
    public static List<String> getYearDateList() {
        List<String> yearDates = new ArrayList<>();
        Date startDate = getCurMonthDate();
        // 定义日期实例
        Calendar dd = Calendar.getInstance();
        // 设置日期起始时间
        dd.setTime(startDate);
        SimpleDateFormat sdf = new SimpleDateFormat(MONTHFORMATTPL);
        for (int i = 0; i < 12; i++) {
            String str = sdf.format(dd.getTime());
            yearDates.add(str);
            dd.add(Calendar.MONTH, 1); //进行当前日期月份加1
        }
        return yearDates;
    }

    public static boolean isValidDate(String str, String pattern) {
        boolean convertSuccess = true;
        // 指定时间格式由外部传入
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        try {
            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证时间，
            // 比如   1）2017/02/29会被接受，并转换成2017/03/01
            //     2）2017-07-01 66:66:66会被接受，并转换成2017-07-03 19:07:06
            format.setLenient(false);
            format.parse(str);
        } catch (ParseException e) {
            // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            convertSuccess = false;
        }
        return convertSuccess;
    }

    /**
     * 获取date后一天的时间
     *
     * @param date
     * @return
     */
    public static Date getNextDate(Date date) {
        if (date == null) {
            return null;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, 1);
        return cal.getTime();
    }

    /**
     * 日期转为指定格式的字符串.
     *
     * @param date 要格式化的日期
     * @return 日期字符串
     */
    public static String format(Date date, String format) {
        if (date == null) {
            return "";
        }

        if (StringUtils.isBlank(format)) {
            format = getDateTimePattern();
        }

        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    private static Integer timeLength = 8;

    public static String timestampToString(String timestamp) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(DATETIMEFORMATTPL);
            if (timestamp.length() == 13) {
                String date = sdf.format(new Date(Long.parseLong(timestamp)));
                //将13位时间戳转化为字符串
                return date;
            } else {
                String date = sdf.format(new Date(Integer.parseInt(timestamp) * 1000L));
                //将10位时间戳转化为字符串
                return date;
            }
        } catch (Exception e) {
            logger.error("时间戳转换成String失败:{}", e);
        }
        return null;
    }

    public static String timestampToStrings(String timestamp) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(SIMPLEDATETIMEFORMATTPL);
            if (timestamp.length() == 13) {
                String date = sdf.format(new Date(Long.parseLong(timestamp)));
                //将13位时间戳转化为字符串
                return date;
            } else {
                String date = sdf.format(new Date(Integer.parseInt(timestamp) * 1000L));
                //将10位时间戳转化为字符串
                return date;
            }
        } catch (Exception e) {
            logger.error("时间戳转换成String失败:{}", e);
        }
        return null;
    }

    public static Integer timeTosecond(String time) {
        Integer lastvalue = 0;
        if (time == null || time.equals("") || time.equals("0")) {
            lastvalue = 0;
            return lastvalue;
        }
        if (time.length() > timeLength) {
            String[] list = time.trim().split("-");
            int days = Integer.valueOf(list[0]) * 3600 * 24;
            int seconds = timeToSecond2(list[1]);
            lastvalue = days + seconds;
            return lastvalue;
        } else {
            lastvalue = timeToSecond2(time);
            return lastvalue;
        }
    }

    private static Integer timeToSecond2(String time) {
        Integer lastvalue = 0;
        try {
            int hours = 0;
            int minutes = 0;
            int seconds = 0;
            String[] list = time.trim().split(":");
            if (list.length == 1) {
                seconds = Integer.valueOf(list[0]);
            } else if (list.length == 2) {
                minutes = Integer.valueOf(list[0]);
                seconds = Integer.valueOf(list[1]);
            } else if (list.length == 3) {
                hours = Integer.valueOf(list[0]);
                minutes = Integer.valueOf(list[1]);
                seconds = Integer.valueOf(list[2]);
            }
            lastvalue = hours * 3600 + minutes * 60 + seconds;
        } catch (Exception e) {
            logger.error("转换时间失败:", e);
            return lastvalue;
        }
        return lastvalue;
    }

    /**
     * 时间戳转为指定格式的日期.
     *
     * @param locationMarkTime 要格式化的日期
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String changeTimeGs(String locationMarkTime) {
        String timeData = "";
        if (null != locationMarkTime && !"".equals(locationMarkTime)) {
            if (locationMarkTime.indexOf('-') != -1) {
                timeData = locationMarkTime;
            } else {
                locationMarkTime = locationMarkTime.substring(0, 4) + "-" + locationMarkTime.substring(4, 6) + "-"
                        + locationMarkTime.substring(6, 8) + " " + locationMarkTime.substring(8, 10) + ":"
                        + locationMarkTime.substring(10, 12) + ":" + locationMarkTime.substring(12, 14);
                timeData = locationMarkTime;
            }
        }
        return timeData;
    }

    /**
     * 获取时间戳
     *
     * @return
     */
    public static Long getTimeStamp() {
        long time = System.currentTimeMillis();
        return time;
    }

    /**
     * 秒转换时间格式
     *
     * @param seconds 要转换的秒数
     * @return HH:mm'ss''
     */
    public static String secondToTime(Integer seconds) {
        if (null == seconds) {
            return "";
        }

        int hour = seconds / 3600;
        int minute = (seconds - hour * 3600) / 60;
        int second = (seconds - hour * 3600 - minute * 60);
        return String.format("%02d:%02d'%02d''", hour, minute, second);
    }

    /**
     * @param @param  dateTime
     * @param @return 参数
     * @return String    返回类型
     * @throws
     * @Title: removeSymbol
     * @Description: 删除时间字符串中的时间符号(空格 、 冒号 、 中横杠)
     * @author HXH
     */
    public static String removeSymbol(String dateTime) {
        Pattern pattern = Pattern.compile("[\\s+|\\-+|\\:+]");
        Matcher matcher = pattern.matcher(dateTime);
        return matcher.replaceAll("");
    }


    // 计算时间差

    /**
     * @param @param  startTime 起始时间戳
     * @param @param  endTime 结束时间戳
     * @param @return 参数
     * @return long    返回毫秒
     * @throws
     * @Title: calculateTime
     * @Description: 计算两个时间差
     * @author HXH
     */
    public static long millisecondsBetween(String beginDateTime, String endDateTime) {
        if (StringUtils.isBlank(beginDateTime) || StringUtils.isBlank(endDateTime)) {
            return -1;
        }
        return getDate(endDateTime).getTime() - getDate(beginDateTime).getTime();
    }

    /**
     * 取得日期是某年的第几周
     *
     * @param date
     * @return
     */
    public static int getWeekOfYear(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int week_of_year = cal.get(Calendar.WEEK_OF_YEAR);
        return week_of_year;
    }

    /**
     * 取得某个月有多少天
     *
     * @param year
     * @param month
     * @return
     */
    public static int getDaysOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month - 1);
        int days_of_month = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        return days_of_month;
    }

    /**
     * 根据日期取得当前星期第几天?
     */
    public static Integer getWeek(Date date) {
        Integer[] weeks = {7, 1, 2, 3, 4, 5, 6};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (week_index < 0) {
            week_index = 0;
        }
        return weeks[week_index];
    }

    /**
     * 获取时间戳
     *
     * @return
     */
    public static Long getTS() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATETIMEMSFORMATTPL);
        LocalDateTime localDateTime = LocalDateTime.parse(DateTimeUtil.getDateTimeString(true), formatter);
        long epochMilli = localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
        return epochMilli;
    }


    /**
     * 获取当前时间前n天或者前n小时或者前n分钟或者前n秒时间
     *
     * @param timeUnit
     * @param amount
     * @return
     */
    public static String getTimeBeforeNow(ChronoUnit timeUnit, long amount) {
        LocalDateTime currentTime = LocalDateTime.now();
        LocalDateTime timeBefore = currentTime.minus(amount, timeUnit);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATETIMEFORMATTPL);
        return timeBefore.format(formatter);
    }

    public static String timestampTransferString(String timestamp) {
        long value = Double.valueOf(timestamp).longValue();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDateFormat.format(new Date(value));
    }

    public static String currentTimeString() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATETIMEMSFORMATTPL);
        return simpleDateFormat.format(new Date());
    }

    /**
     * 分割时间段 - 非严格分层
     *
     * @param start 起始时间
     * @param end   结束时间
     * @param level 分割层数
     * @return java.util.List<java.util.Date>
     * @author ly
     */
    public static List<Date> splitDate(Date start, Date end, Long level) {
        // 小于1层的
        if (start.equals(end) || level == null || level < 2) {
            return Arrays.asList(start, end);
        }
        // 校验大小
        boolean order = start.before(end);
        start = order ? start : end;
        end = order ? end : start;

        // 获取间隔
        long min = start.getTime();
        long max = end.getTime();
        long step = (max - min) / level;

        // 由于大部分情况下，差值无法整除level，所以仅取值为level上一级，并最后添加最大值
        List<Date> list = LongStream.range(0, level).mapToObj(i -> new Date(min + (i * step))).collect(Collectors.toList());
        list.add(end);
        return list;
    }


    public static void main(String[] args) {
        Long ts = getTS();
        System.out.println(ts);
    }
}
